#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netdb.h>
#include <dirent.h>
#include <fcntl.h>
#include <signal.h>


#define ALIAS_LEN_MAX		20
#define MSG_BODY_MAX		80

#define ACT_LOGIN			(1)
#define ACT_LOGOUT			(0xffffffff)
#define ACT_CHAT			(0)

#define REG_OK				1
#define REG_FAIL			-1

struct MSG
{
	int	act;
	int id;
	char alias[ALIAS_LEN_MAX];
	char body[MSG_BODY_MAX];
};


int login(const char *alias, int sock, const struct sockaddr *name, socklen_t name_len)
{
	int ret;
	struct MSG msg;
	memset(&msg, 0, sizeof(msg));

	msg.act = ACT_LOGIN;
	strncpy(msg.alias, alias, strlen(alias));

	ret = sendto(sock, &msg, sizeof(msg), 0, name, name_len);
	if(ret < 0){
		perror("sendto");
		return -1;
	}

	return 0;
}

int logout(int sock, const struct sockaddr *name, socklen_t name_len)
{
	int ret;
	struct MSG msg;
	memset(&msg, 0, sizeof(msg));

	
}

int main(int argc, char *argv[])
{
	int sock;
	int ret;
	int pid;
	int i;
	int regstatus = 0;
	char *args[10];
	unsigned short port;
	char buf[1024];
	struct sockaddr_in name;
	struct hostent *tmp;
	socklen_t name_len;
	
	if(argc != 3){
		fprintf(stderr, "Usage: URL[IP] Port.\n");
		exit(1);
	}

	sock = socket(AF_INET, SOCK_DGRAM, 0);
	if(sock < 0){
		perror("socket");
		exit(-1);
	}

	port = (unsigned short)atoi(argv[2]);
	tmp = gethostbyname(argv[1]);

	memset(&name, 0, sizeof(name));
	name.sin_family = AF_INET;
	name.sin_port = htons(port);
	name.sin_addr = *(struct in_addr *)tmp->h_addr;

	pid = fork();
	if(pid < 0){
		perror("fork");
		exit(-1);
	}
	if(pid > 0){
		while(1)
		{
			memset(buf, 0, sizeof(buf));
			ret = recvfrom(sock, buf, sizeof(buf), 0, (struct sockaddr *)&name.sin_addr, &name_len);
			if(ret <= 0){
				perror("recvfrom");
			}
			printf("<server> %s\n", buf);
		}
	}else{
		while(1)
		{
			memset(buf, 0, sizeof(buf));
			fprintf(stderr, ">>");
			
			fgets(buf, 1024, stdin);
			buf[strlen(buf) - 1] = 0;

			i = 0;
			args[i] = strtok(buf, " ");
			while(args[i] != NULL)
			args[++i] = strtok(NULL, " ");

			if(strcmp(args[0], "login") == 0){
				if(login(args[1], sock, (struct sockaddr *)&name, name_len) < 0){
					fprintf(stderr, "login failed\n");
					kill(pid, SIGKILL);
					exit(-1);
				}
			}
			if(strcmp(args[0], "quit") == 0){
				
			}
			
			
		}
	}

	
}
